import { reqCartList, reqDeleteCartById, reqUpdateCheckCartById } from '@/api/index';

let state = {
    cartList: [],
};

let mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList;
    }
};

let actions = {
    async getCartList({ commit }) {
        let result = await reqCartList();
        if (result.code == 200) {
            commit('GETCARTLIST', result.data);
        }
    },
    /* eslint-disable */
    async deleteCartById({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject();
        }
    },
    /* eslint-disable */
    /* eslint-disable */
    async updateCheckCartById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckCartById(skuId, isChecked);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject();
        }
    },
    /* eslint-disable */
    //删除所有选中的商品
    deleteAllCheckedCart({ getters, dispatch }) {
        let arr = [];
        //获取仓库里面购物车的数据
        getters.cartList.cartInfoList.forEach(item => {
            //商品的勾选状态是勾选的,发请求一个一个删除
            if (item.isChecked == 1) {
                let ps = dispatch('deleteCartById', item.skuId);
                arr.push(ps);
            }
        })
        return Promise.all(arr);
    },
    //更新全选或者全不选的状态
    updateAllCartChecked({ getters, dispatch }, isChecked) {
        let arr = [];
        getters.cartList.cartInfoList.forEach(item => {
            let ps = dispatch('updateCheckCartById', { skuId: item.skuId, isChecked });
            arr.push(ps);
        });
        return Promise.all(arr);
    }
};

let getters = {
    cartList(state) {
        return state.cartList[0] || []
    }
};


export default {
    state,
    mutations,
    actions,
    getters
}